import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent))

# 参考mcp server的官方文档

import sys
from pathlib import Path
# 在 weather_baidu_webapi.py 文件开头添加
project_root = Path(__file__).parent.parent.parent.parent  # 根据实际情况调整
sys.path.append(str(project_root))

# weather_mcp_server.py 增强版
from fastapi import FastAPI
from api import weather_baidu_webapi
from mcp.server.fastmcp import FastMCP
import uvicorn
import logging

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Initialize FastMCP server
# mcp = FastMCP("weather")

app = FastAPI()
mcp = FastMCP("weather", app=app)  # 关联到FastAPI实例

@app.get("/weather/get-weather", tags=["weather"], summary="获取天气数据", description="获取指定地区的天气数据，支持all/temperature/humidity类型")
@mcp.tool()
async def get_weather(district_id: str, data_type: str, debug: bool = False) -> dict:
    """获取天气数据
    Args:
        district_id: 地区ID
        data_type: 数据类型(all/temperature/humidity)
        debug: 调试模式
    Returns:
        天气数据dict(返回结构化数据而非字符串)
    """
    try:
        result = await weather_baidu_webapi.get_weather(district_id, data_type, debug)
        return {
            "success": True,
            "data": result,
            "district_id": district_id,
            "data_type": data_type,
            "debug": debug
        }
    except Exception as e:
        logger.error(f"Weather API error: {e}")
        return f"Error getting weather: {str(e)}"

if __name__ == "__main__":
    # 自动检测运行环境
    if "--stdio" in sys.argv:
        logger.info("Running in stdio mode")
        mcp.run()  # 假设FastMCP支持stdio模式
    else:
        logger.info("Running HTTP server")
        import uvicorn
        uvicorn.run(app, host="127.0.0.1", port=8001)
